package chan.project.template;

import chan.project.common.ErrorCode;
import chan.project.exception.ThrowUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@Component
public class FilePictureUpload extends PictureUploadTemplate{

    @Override
    public void validFile(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        //校验文件是否为空
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR);
        //校验文件大小
        final long MAX = 10 * 1024 * 1024L;
        ThrowUtils.throwIf(multipartFile.getSize() > MAX,ErrorCode.PARAMS_ERROR,"文件大小不能超过10MB");
        //校验文件后缀
        String originalFilename = multipartFile.getOriginalFilename();
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("png", "jpeg", "jpg", "webp");
        ThrowUtils.throwIf(ALLOW_FORMAT_LIST.contains(originalFilename),ErrorCode.PARAMS_ERROR,"文件类型错误");
    }

    @Override
    public String getOriginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    public void saveFile(Object inputSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }
}
